function getCookie(name) {
    var r = document.cookie.match("\\b" + name + "=([^;]*)\\b");
    return r ? r[1] : undefined;
}


$(function(){
    // 滚动到顶部
    window.scrollTo(0, 0);

    // 打开登录框
    $('.comment_form_logout').click(function () {
        $('.login_form_con').show();
    });

    // 收藏
    $(".collection").click(function () {
        var news_id = $(".collection").attr('data-newid');
        var action = "collect";
        var param = {
            "news_id": news_id,
            "action": action
        };
        $.ajax({
            url: "/news/news_collect",
            type: 'POST',
            contentType: 'application/json',
            dataType: 'json',
            data: JSON.stringify(param),
            headers: {
                "X-CSRFToken": getCookie("csrf_token")
            },
            success: function (resp) {
                if(resp.errno == '0'){
                    // 收藏成功,页面局部刷新
                    // 隐藏收藏按钮
                    $(".collection").hide();
                    // 显示取消收藏按钮
                    $(".collected").show();
                }else if(resp.errno == '4101'){
                    // 用户未登录,自动弹出登录界面
                    $('.login_form_con').show();
                }else{
                    alert(resp.errmsg)
                }
            }
        })

    });

    // 取消收藏
    $(".collected").click(function () {
        var news_id = $(".collection").attr('data-newid');
        var action = "cancel_collect";
        var param = {
            "news_id": news_id,
            "action": action
        };
        $.ajax({
            url: "/news/news_collect",
            type: 'POST',
            contentType: 'application/json',
            dataType: 'json',
            data: JSON.stringify(param),
            headers: {
                "X-CSRFToken": getCookie("csrf_token")
            },
            success: function (resp) {
                if(resp.errno == '0'){
                    // 取消收藏成功,页面局部刷新
                    // 显示收藏按钮
                    $(".collection").show();
                    // 隐藏取消收藏按钮
                    $(".collected").hide();
                }else{
                    alert(resp.errmsg)
                }
            }
        })
     
    });

        // 评论提交
    $(".comment_form").submit(function (e) {
        // 阻止表单默认提交操作
        e.preventDefault();
        var news_id = $(".comment_form").attr("data-newsid");
        var content = $(".comment_input").val();
        if(!content){
            alert("请输入评论内容");
            return;
        }
        var param = {
            "news_id": news_id,
            "content": content
        };
        $.ajax({
            url: "/news/news_comment",
            type: 'POST',
            contentType: 'application/json',
            dataType: 'json',
            data: JSON.stringify(param),
            headers: {
                "X-CSRFToken": getCookie("csrf_token")
            },
            success: function (resp) {
                if(resp.errno == '0'){
                    // 评论成功，页面局部刷新
                    var comment = resp.data;
                    // 拼接内容
                    var comment_html = '';
                    comment_html += '<div class="comment_list">';
                    comment_html += '<div class="person_pic fl">';
                    if (comment.user.avatar_url) {
                        comment_html += '<img src="' + comment.user.avatar_url + '" alt="用户图标">'
                    }else {
                        comment_html += '<img src="../../static/news/images/person01.png" alt="用户图标">'
                    }
                    comment_html += '</div>';
                    comment_html += '<div class="user_name fl">' + comment.user.nick_name + '</div>';
                    comment_html += '<div class="comment_text fl">';
                    comment_html += comment.content;
                    comment_html += '</div>';
                    comment_html += '<div class="comment_time fl">' + comment.create_time + '</div>';

                    comment_html += '<a href="javascript:;" class="comment_up fr" data-commentid="' + comment.id + '" data-newsid="' + comment.news_id + '">赞</a>';
                    comment_html += '<a href="javascript:;" class="comment_reply fr">回复</a>';
                    comment_html += '<form class="reply_form fl" data-commentid="' + comment.id + '" data-newsid="' + news_id + '">';
                    comment_html += '<textarea class="reply_input"></textarea>';
                    comment_html += '<input type="button" value="回复" class="reply_sub fr">';
                    comment_html += '<input type="reset" name="" value="取消" class="reply_cancel fr">';
                    comment_html += '</form>';

                    comment_html += '</div>';
                    // 拼接到内容的前面
                    $(".comment_list_con").prepend(comment_html);
                    // 让comment_sub 失去焦点
                    $('.comment_sub').blur();
                    // 清空输入框内容
                    $(".comment_input").val("");
                    // window.location.reload()
                    // 更新评论条数
                    updateCommentCount();
                }else{
                    alert(resp.errmsg)
                }
            }
        });

    });

    $('.comment_list_con').delegate('a,input','click',function(){

        var sHandler = $(this).prop('class');

        if(sHandler.indexOf('comment_reply')>=0)
        {
            $(this).next().toggle();
        }

        if(sHandler.indexOf('reply_cancel')>=0)
        {
            $(this).parent().toggle();
        }

        if(sHandler.indexOf('comment_up')>=0)
        {
            var $this = $(this);
            var comment_id = $this.attr('data-commentid');
            var action = '';
            var like_count = $this.attr("data-likecount");
            if (like_count == undefined) {
                like_count = 0
            }
            if(sHandler.indexOf('has_comment_up')>=0)
            {
                // 如果当前该评论已经是点赞状态，再次点击会进行到此代码块内，代表要取消点赞
                // $this.removeClass('has_comment_up');
                // 取消点赞
                action = "remove";
                var param = {
                    "comment_id": comment_id,
                    "action": action
                };
                $.ajax({
                    url: "/news/comment_like",
                    type: 'POST',
                    contentType: 'application/json',
                    dataType: 'json',
                    data: JSON.stringify(param),
                    headers: {
                        "X-CSRFToken": getCookie("csrf_token")
                    },
                    success: function (resp) {
                        if(resp.errno == '0'){
                            // 取消点赞成功,页面局部刷新
                            // 改变按钮样式
                            $this.removeClass('has_comment_up');
                            like_count = parseInt(like_count) - 1;
                            $this.attr("data-likecount", like_count);
                            if(like_count == 0){
                                $this.html("赞")
                            }else{
                                $this.html(like_count)
                            }
                        }else if(resp.errno == '4101'){
                            // 用户未登录,自动弹出登录界面
                            $('.login_form_con').show();
                        }else{
                            alert(resp.errmsg)
                        }
                    }
                })
            }else {
                // $this.addClass('has_comment_up');
                // 点赞
                action = "add";
                var param = {
                    "comment_id": comment_id,
                    "action": action
                };
                $.ajax({
                    url: "/news/comment_like",
                    type: 'POST',
                    contentType: 'application/json',
                    dataType: 'json',
                    data: JSON.stringify(param),
                    headers: {
                        "X-CSRFToken": getCookie("csrf_token")
                    },
                    success: function (resp) {
                        if(resp.errno == '0'){
                            // 取消点赞成功,页面局部刷新
                            // 改变按钮样式
                            $this.addClass('has_comment_up');
                            like_count = parseInt(like_count) + 1;
                            $this.attr("data-likecount", like_count);
                            if(like_count == 0){
                                $this.html("赞")
                            }else{
                                $this.html(like_count)
                            }
                        }else if(resp.errno == '4101'){
                            // 用户未登录,自动弹出登录界面
                            $('.login_form_con').show();
                        }else{
                            alert(resp.errmsg)
                        }
                    }
                })
            }
        }

        if(sHandler.indexOf('reply_sub')>=0)
        {
            // 回复评论
            var $this_sub = $(this);
            var news_id = $this_sub.parent().attr("data-newsid");
            var parent_id = $this_sub.parent().attr("data-commentid");
            var content = $this_sub.prev().val();
            if(!content){
                alert("请输入评论内容");
                return;
            }
            var param = {
                "news_id": news_id,
                "content": content,
                "parent_id": parent_id
            };
            $.ajax({
                url: "/news/news_comment",
                type: 'POST',
                contentType: 'application/json',
                dataType: 'json',
                data: JSON.stringify(param),
                headers: {
                    "X-CSRFToken": getCookie("csrf_token")
                },
                success: function (resp) {
                    if(resp.errno == '0'){
                        // 回复评论成功，页面局部刷新
                        var comment = resp.data;
                        // 拼接内容
                        var comment_html = "";
                        comment_html += '<div class="comment_list">';
                        comment_html += '<div class="person_pic fl">';
                        if (comment.user.avatar_url) {
                            comment_html += '<img src="' + comment.user.avatar_url + '" alt="用户图标">'
                        }else {
                            comment_html += '<img src="../../static/news/images/person01.png" alt="用户图标">'
                        }
                        comment_html += '</div>';
                        comment_html += '<div class="user_name fl">' + comment.user.nick_name + '</div>';
                        comment_html += '<div class="comment_text fl">';
                        comment_html += comment.content;
                        comment_html += '</div>';
                        comment_html += '<div class="reply_text_con fl">';
                        comment_html += '<div class="user_name2">' + comment.parent.user.nick_name + '</div>';
                        comment_html += '<div class="reply_text">';
                        comment_html += comment.parent.content;
                        comment_html += '</div>';
                        comment_html += '</div>';
                        comment_html += '<div class="comment_time fl">' + comment.create_time + '</div>';

                        comment_html += '<a href="javascript:;" class="comment_up fr" data-commentid="' + comment.id + '" data-newsid="' + comment.news_id + '">赞</a>';
                        comment_html += '<a href="javascript:;" class="comment_reply fr">回复</a>';
                        comment_html += '<form class="reply_form fl" data-commentid="' + comment.id + '" data-newsid="' + news_id + '">';
                        comment_html += '<textarea class="reply_input"></textarea>';
                        comment_html += '<input type="button" value="回复" class="reply_sub fr">';
                        comment_html += '<input type="reset" name="" value="取消" class="reply_cancel fr">';
                        comment_html += '</form>';

                        comment_html += '</div>';
                        $(".comment_list_con").prepend(comment_html);
                        // 请空输入框
                        $this_sub.prev().val('');
                        // 表单隐藏
                        $this_sub.parent().hide();
                        // 更新评论条数
                        updateCommentCount();
                    }else{
                        alert(resp.errmsg)
                    }
                }
            });

        }
    });

        // 关注当前新闻作者
    $(".focus").click(function () {
        var author_id = $(this).attr('data-userid');
        var action = 'follow';
        param = {
            "author_id": author_id,
            "action": action
        };
        $.ajax({
            url: "/news/followed_user",
            type: 'POST',
            contentType: 'application/json',
            dataType: 'json',
            data: JSON.stringify(param),
            headers: {
                "X-CSRFToken": getCookie("csrf_token")
            },
            success: function (resp) {
                if(resp.errno == '0'){
                    // 关注成功，局部刷新界面
                    $(".focus").hide();
                    $(".focused").show();
                    // 粉丝数变化
                    var follows = $(".follows b").html();
                    follows = parseInt(follows) + 1;
                    $(".follows b").html(follows)
                }else if (resp.errno == "4101") {
                    // 未登录，弹出登录框
                    $('.login_form_con').show();
                }else{
                    alert(errmsg)
                }
            }
        })

    });

    // 取消关注当前新闻作者
    $(".focused").click(function () {
        var author_id = $(this).attr('data-userid');
        var action = 'unfollow';
        param = {
            "author_id": author_id,
            "action": action
        };
        $.ajax({
            url: "/news/followed_user",
            type: 'POST',
            contentType: 'application/json',
            dataType: 'json',
            data: JSON.stringify(param),
            headers: {
                "X-CSRFToken": getCookie("csrf_token")
            },
            success: function (resp) {
                if(resp.errno == '0'){
                    // 取消关注成功，局部刷新界面
                    $(".focus").show();
                    $(".focused").hide();
                    // 粉丝数变化
                    var follows = $(".follows b").html();
                    follows = parseInt(follows) - 1;
                    $(".follows b").html(follows)
                }else{
                    alert(errmsg)
                }
            }
        })
    })
});


// 更新评论条数
function updateCommentCount() {
    var length = $(".comment_list").length;
    $(".comment_count").html(length + "条评论")
}